﻿var vm = this.lookupViewModel();

//查看视图隐藏copy按钮
if (this.analysis.status == 'view') {
    btns.forEach(
        function (btn) {
            if (btn.action == 'PA_Copy') {
                btn.hidden = true;
            }
        }
    );
}
var ExpenseType = vm.get('NebulogyForm.GeneralInformation.ExpenseType');
if (ExpenseType == "6") {
    btns.forEach(function (btn) {
        if (btn.action == 'AddsignToCJRL') {
            btn.hidden = true;
        }
    });
}
//如果是Enquire的时候将resubmit按钮的名称改为Answer
var isEnquiry = vm.get('NebulogyForm.isInquiryCall');
if (this.analysis.status == 'resubmit') {
    if (isEnquiry == 1) {
        btns.forEach(function (btn) {
            if (btn.action == 'Resubmit') {
                btn.text = 'Answer';
            } else if (btn.action == 'PA_JabilCancel') {
                ///如果是Enquire的时候隐藏作废按钮
                btn.hidden = true;
            }
        });
    }
}

//默认赋值.
vm.set('NebulogyForm.receiveEmpIds', []);
vm.set('NebulogyForm.receiveEmpNames', '');

var me = this;

//发起和流程结束不允许沟通.流程结束 会在init事件自动隐藏currentApprover. 所以可以根据该控件的隐藏和显示判断.
//2019:09.24 沟通功能这次不上线. 通过URL 判断.
var isDev = window.location.origin.indexOf('moffice.jlrinfo.cn') == -1 && window.location.origin.indexOf('bpm.jlrinfo.cn') == -1;

if (vm.get('NebulogyForm.procInstId') && !ref.currentApprover.hidden && isDev) {

    btns.push({
        text: 'Communication',
        listeners: {
            click: function () {
                var win = Ext.create('Ext.window.Window', {
                    title: 'Communication',
                    width: 950,
                    height: 600,
                    modal: true,
                    padding: 10,
                    layout: 'fit',
                    cls: 'form-theme landRover',
                    items: {
                        xtype: "paigrid",
                        mobileDisplay: true,
                        pcDisplay: true,
                        PrintDisplay: true,
                        hidden: false,
                        readOnly: false,
                        readOnlyHead: true,
                        name: "datagrid1",
                        editable: false,
                        enableRowStatus: false,
                        enableAdd: false,
                        enablePaging: true,
                        enableActions: false,
                        reference: "datagrid1",
                        enableSearch: false,
                        dockedItems: [{
                            xtype: 'toolbar',
                            dock: 'top',
                            items: {
                                xtype: "paitriggerfield",
                                readOnly: false,
                                fieldLabel: language("Chooese Employee"),
                                questionTip: language(""),
                                name: "ChooeseEmployee",
                                reference: 'ce',
                                reference: "Chooese Employee",
                                editable: false,
                                labelAlign: "left",
                                labelWidth: 120,
                                flex: 1,
                                listeners: {
                                    triggerclick: function (trigger, field, e) {
                                        var ref = me.lookupController().getReferences();
                                        var vm = me.lookupViewModel();

                                        Ext.getBody().mask();
                                        if (!field.win) {
                                            Ext.require([
                                                'PAI.ux.panel.selection.OrgEmpSelectionComp',
                                                'PAI.ux.window.selection.SingleSelectionWin',
                                                'PAI.ux.panel.selection.EmpSelectionComp'
                                            ], function () {
                                                field.win = Ext.create({
                                                    title: 'Select Staff',
                                                    xtype: 'singleselectionwin',
                                                    selectType: 'empselection',
                                                    isMulti: true,
                                                    closeAction: 'hide',
                                                    needOrderByUs: false,
                                                    modal: true,
                                                    requestParams: [{
                                                        name: 'id'
                                                    }, {
                                                        name: 'firstName'
                                                    }, {
                                                        name: 'lastName'
                                                    }, {
                                                        name: 'defaultLanguage'
                                                    }],
                                                    listeners: {
                                                        selectionchange: function (win, records) {

                                                            if (!Ext.isEmpty(records)) {

                                                                var receiveEmpIds = [],
                                                                    receiveEmpNames = [];

                                                                Ext.each(records, function (record) {
                                                                    receiveEmpIds.push(record.id);
                                                                    receiveEmpNames.push(record.lastName + ' ' + record.firstName);
                                                                });

                                                                vm.set('NebulogyForm.receiveEmpIds', receiveEmpIds);
                                                                vm.set('NebulogyForm.receiveEmpNames', receiveEmpNames.join());

                                                                field.setValue(receiveEmpNames);
                                                            }
                                                        },
                                                        close: function () {
                                                            Ext.getBody().unmask();
                                                        }
                                                    }
                                                }).show();
                                            });
                                        } else {
                                            field.win.show();
                                        }
                                    }
                                }
                            }
                        }, {
                            xtype: 'toolbar',
                            dock: 'bottom',
                            items: {
                                xtype: 'textarea',
                                fieldLabel: 'Comment',
                                flex: 1
                            }
                        }],
                        columns: [{
                            text: language("Employee Name"),
                            dataIndex: "sendEmpName",
                            minWidth: 100,
                            flex: 1
                        }, {
                            text: language("Content"),
                            dataIndex: "content",
                            minWidth: 100,
                            flex: 1
                        }, {
                            text: language("Create date"),
                            dataIndex: "created_date",
                            minWidth: 100,
                            flex: 1,
                            renderer: formatDate
                        }],
                        store: {
                            type: 'store',
                            autoLoad: true,
                            fields: [
                                { name: "id" },
                                { name: "procInstId" },
                                { name: "type" },
                                { name: "destInstId" },
                                { name: "created_date" },
                                { name: "sendEmpId" },
                                { name: "sendEmpName" },
                                { name: "content" }
                            ],
                            proxy: {
                                type: 'pai.rest',
                                ns: PAI.application.userServerUrl,
                                requestName: 'ObjectQuery',
                                reader: {
                                    rootProperty: "result"
                                }
                            },
                            listeners: {
                                beforeload: function (store) {
                                    var sql = {
                                        registryCenterId: '8d206e31-2189-492d-81b8-70dab16a7f6f',
                                        sqlParam: {
                                            "@procInstId": vm.get('NebulogyForm.procInstId'),
                                        }
                                    };
                                    store.proxy.setExtraParams(sql);
                                },
                                load: function (store) {
                                    store.filterBy(function (record) {
                                        return record.get('procInstId') != null;
                                    });
                                }
                            }
                        },
                        plugins: {
                            rowexpander: {
                                rowBodyTpl: new Ext.XTemplate(
                                    '<tpl if="content">',
                                    '<div class="formhistory-expansion">' +
                                    '<b>Content: </b>: {content}' +
                                    '</div>' +
                                    '<div class="formhistory-expansion" style="padding-left:20px;">',
                                    '{[this.showDetail(values.id)]}',
                                    '</div>',
                                    '</tpl>',
                                    {
                                        showDetail: function (id) {
                                            var html = '',
                                                tpl = '<p><b>Replier: </b>{0}</p>' +
                                                    '<p><b>Reply Date: </b>{1}</p>' +
                                                    '<p><b>Reply content: </b>{2}</p>' +
                                                    '<hr style="height:1px;border:none;border-top:1px solid #a7a7a7;" />';
                                            Ext.PAIRest.request({
                                                ns: PAI.application.url,
                                                url: 'last/communicationDetailObj/page?_dc=' + Date.now(),
                                                method: "POST",
                                                async: false,
                                                data: {
                                                    pId: id
                                                },
                                                success: function (data) {

                                                    Ext.each(data.communicationDetailObjList, function (item) {
                                                        html += Ext.String.format(tpl, item.receiveLastName + ' ' + item.receiveFirstName, formatDate(item.replyDate), item.content);
                                                    });

                                                }
                                            });
                                            return html;
                                        }
                                    }
                                )
                            }

                        }
                    },
                    buttons: [{
                        text: 'Confirm',
                        handler: function () {
                            var grid = win.down('grid');

                            var emp = PAI.Global.getAccount().employee;
                            var destInstId = PAI.Global.getUrlData('destInstId');
                            var detailId = PAI.Global.getUrlData('detailId');
                            var procInstId = vm.get('NebulogyForm.procInstId');
                            var sn = PAI.Global.getUrlData('sn').split('_');
                            var receiveEmpIds = vm.get('NebulogyForm.receiveEmpIds');
                            var content = win.down('textarea').getValue();
                            var selectRecord = grid.getSelection();
                            var canClose = false;
                            //生成新的id

                            var uuidModel = Ext.define('MyApp.data.MyModelY', {
                                extend: 'Ext.data.Model',
                                identifier: 'uuid'
                            });

                            var uuid = uuidModel.create().id;
                            if (!content) {
                                Ext.Msg.alert('Tips', 'Please enter your Comment!');
                                return;
                            }
                            else if (receiveEmpIds.length == 0 && selectRecord.length == 0) {
                                Ext.Msg.alert('Tips', 'Please choose the way you want to communicate!');
                                return;
                            }
                            else if (receiveEmpIds.length > 0 && selectRecord.length > 0) {
                                win.down('paitriggerfield').setValue('');
                                vm.set('NebulogyForm.receiveEmpIds', []);
                                vm.set('NebulogyForm.receiveEmpNames', '');
                                grid.setSelection(null);

                                Ext.Msg.alert('Tips', 'You can only choose one way to communicate!');
                                return;
                            }
                            //选择了人员.创建新的沟通.
                            else if (receiveEmpIds.length > 0) {
                                var receiveEmpNames = vm.get('NebulogyForm.receiveEmpNames').split(',');

                                Ext.PAIRest.request({
                                    ns: PAI.application.url,
                                    url: 'last/communicationObj',
                                    method: "POST",
                                    async: false,
                                    data: {
                                        id: uuid,
                                        type: 0,
                                        empId: emp.id,
                                        idPath: '/00000000-0000-0000-0000-000000000000/' + uuid,
                                        content: content,
                                        detailId: null,
                                        lastName: emp.lastName,
                                        firstName: emp.firstName,
                                        partentId: '00000000-0000-0000-0000-000000000000',
                                        destInstId: destInstId,
                                        procInstId: procInstId,
                                        k2ActInstId: sn.length > 1 ? sn[1] : 0,
                                        receiveEmpIds: receiveEmpIds.join()
                                    },
                                    success: function (data) {
                                        canClose = true;
                                    }
                                });

                                Ext.each(receiveEmpIds, function (empId, index) {
                                    updateDetail(uuid, empId, receiveEmpNames[index].split(' ')[0], receiveEmpNames[index].split(' ')[1]);
                                });

                                function updateDetail(pid, empId, emplastName, empfirstName) {

                                    Ext.PAIRest.request({
                                        ns: PAI.application.url,
                                        url: 'last/communicationDetailObj',
                                        method: "POST",
                                        async: false,
                                        data: {
                                            id: uuidModel.create().id,
                                            pId: '96dc6186-e458-4c70-af5a-70954b26c493',
                                            pid: pid,
                                            status: 0,
                                            content: '',
                                            replyDate: null,
                                            procInstId: procInstId,
                                            receiveEmpId: empId,
                                            receiveLastName: emplastName,
                                            receiveFirstName: empfirstName
                                        },
                                        success: function (data) {
                                            canClose = true;
                                        }
                                    });
                                }
                            }
                            //被沟通人员进来.
                            else if (selectRecord.length > 0) {

                                var currentEmp = selectRecord[0];

                                Ext.PAIRest.request({
                                    ns: PAI.application.url,
                                    url: 'last/communicationDetailObj/page?_dc=' + Date.now(),
                                    method: "POST",
                                    async: false,
                                    data: {
                                        pId: currentEmp.get('id'),
                                        receiveEmpId: emp.id
                                    },
                                    success: function (data) {

                                        if (data.communicationDetailObjList.length) {
                                            var obj = data.communicationDetailObjList[0];

                                            if (obj.status == 1) {
                                                Ext.Msg.alert('Tips', 'The selected data has been replied!');
                                            } else {
                                                canClose = true;
                                                updateDetail(obj.id);
                                            }
                                        } else {
                                            Ext.Msg.alert('Tips', 'You have no right to reply to the currently selected data!');
                                        }
                                    }
                                });

                                function updateDetail(detailId) {
                                    Ext.PAIRest.request({
                                        ns: PAI.application.url,
                                        url: 'last/communicationDetailObj',
                                        method: "PUT",
                                        async: false,
                                        data: {
                                            id: detailId,
                                            status: 1,
                                            content: content,
                                            replyDate: new Date(),
                                            procInstId: procInstId,
                                            receiveEmpId: emp.id,
                                            receiveLastName: emp.lastName,
                                            receiveFirstName: emp.firstName
                                        },
                                        success: function (data) {
                                            grid.store.load();
                                        }
                                    });
                                }
                            }
                            if (canClose) {
                                win.close();
                            }
                        }
                    }]
                }).show();
            }
        }
    });
}

function formatDate(_date) {

    if (_date) {
        var startDate = null;

        if (Ext.isString(_date)) {
            startDate = Ext.Date.parse(_date, 'C', true);
            if (Ext.isEmpty(startDate))
                startDate = Ext.Date.parse(_date, "Y-m-d H:i", true);
        }
        startDate = Ext.Date.format(startDate, 'Y-m-d H:i');

        return startDate;
    }
}